package com.feidee.data.email.util;

import com.feidee.data.email.dao.ConfDao;
import com.feidee.data.email.dao.impl.ConfDaoImpl;
import com.feidee.data.email.model.EConstant;
import com.feidee.data.email.model.EmailConf;
import com.feidee.data.email.model.ScheduleJob;
import com.feidee.data.report.exception.DataDaoException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class QuartzJobFactory implements Job {

  private static final Logger LOG = LoggerFactory.getLogger(QuartzJobFactory.class);


  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
    LOG.info("执行邮件发送任务: email_key=" + scheduleJob.getJobName() + " time=" + EmailUtil.getNowTime());
    HttpClient client = new DefaultHttpClient();
    String url = EConstant.EMAIL_QUARTZ_URL + "&email_key=" + scheduleJob.getJobName();

    ConfDao dao = ApplicationContextUtil.getBean(ConfDaoImpl.class);

    try {
      EmailConf emailConf = dao.getEmailConf(scheduleJob.getJobName());
      if (emailConf.getSend_mail() != 0) {
        url += "&sendEmail=false";
      }
      HttpGet get = new HttpGet(url);
      HttpResponse response = null;
      response = client.execute(get);
      HttpEntity entity = response.getEntity();
      InputStream in = entity.getContent();
      String str = convertStreamToString(in);
      LOG.info("邮件执行结果: " + str);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }
}
